package net.maku.events.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import lombok.AllArgsConstructor;
import net.maku.events.entity.UserSnapshotEntity;
import net.maku.framework.common.utils.PageResult;
import net.maku.framework.mybatis.service.impl.BaseServiceImpl;
import net.maku.events.convert.UserCommentConvert;
import net.maku.events.entity.UserCommentEntity;
import net.maku.events.query.UserCommentQuery;
import net.maku.events.vo.UserCommentVO;
import net.maku.events.dao.UserCommentDao;
import net.maku.events.service.UserCommentService;
import net.maku.member.dao.MemberUserDao;
import net.maku.member.entity.MemberUserEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户评论
 *
 * @author 阿沐 babamu@126.com
 * @since 1.0.0 2025-04-09
 */
@Service
@AllArgsConstructor
public class UserCommentServiceImpl extends BaseServiceImpl<UserCommentDao, UserCommentEntity> implements UserCommentService {

    private final MemberUserDao memberUserDao;

    @Override
    public PageResult<UserCommentVO> page(UserCommentQuery query) {
        IPage<UserCommentEntity> page = baseMapper.selectPage(getPage(query), getWrapper(query));

        return new PageResult<>(UserCommentConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
    }

    private LambdaQueryWrapper<UserCommentEntity> getWrapper(UserCommentQuery query) {
        LambdaQueryWrapper<UserCommentEntity> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotEmpty(query.getUserName())) {
            List<MemberUserEntity> entityList = memberUserDao.selectList(new LambdaQueryWrapper<MemberUserEntity>().like(MemberUserEntity::getRealName, query.getUserName()));
            if (CollectionUtils.isNotEmpty(entityList)) {
                wrapper.in(UserCommentEntity::getUserId, entityList.stream().map(MemberUserEntity::getId).toList());
            } else {
                wrapper.eq(UserCommentEntity::getId, 0);
            }
        }
        return wrapper.orderByDesc(UserCommentEntity::getCreateTime);
    }

    @Override
    public void save(UserCommentVO vo) {
        UserCommentEntity entity = UserCommentConvert.INSTANCE.convert(vo);

        baseMapper.insert(entity);
    }

    @Override
    public void update(UserCommentVO vo) {
        UserCommentEntity entity = UserCommentConvert.INSTANCE.convert(vo);

        updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);
    }

}